
# IMPORTS

from http import cookies
import requests
from requests_html import HTMLSession

from log import logger
from utils import parse_1secmail_mail


# SETUP

from requests.packages.urllib3 import disable_warnings
from requests.packages.urllib3.exceptions import InsecureRequestWarning

disable_warnings(InsecureRequestWarning)


# MAIN

def check_profile(cookies, proxies, user_agent):

    if cookies:
        cookies = {
            'session': cookies['session'],
            'access_token': cookies['access_token'],
            'refresh_token': cookies['refresh_token'],
        }

    headers = {
        'Host': 'myriaverse-api.myria.com',
        'User-Agent': user_agent,
        'Accept': 'application/json',
        'Accept-Language': 'en-US,en;q=0.5',
        # 'Accept-Encoding': 'gzip, deflate',
        'Referer': 'https://myriaverse-api.myria.com/',
        'Cache-Control': 'no-cache',
        'Origin': 'https://myria.com',
        'Dnt': '1',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Gpc': '1',
        # Requests doesn't support trailers
        # 'Te': 'trailers',
        # Requests sorts cookies= alphabetically
        # 'Cookie': f'session={session}; access_token={access_token}; refresh_token={refresh_token}',
    }

    response = requests.get(
        'https://myriaverse-api.myria.com/v1/sigil/users/profile',
        cookies=cookies, headers=headers, proxies=proxies, verify=False
    )

    if response.status_code != 200:
        logger.error(f'code: 9vcqdDXt; {response.status_code} {response.text}')
        return {'status': 'error'}
    if not response.text or not response.json():
        logger.error(f'code: 6NqGfM43; {response.text}')
        return {'status': 'error'}

    if response.json()['status'] != 'success':
        logger.error(f'code: GV8u9QBc;{response.text}')
        return {'status': 'error'}

    return {
        'status': 'success',
        'data': response.json()['data']
    }

def get_server_time(proxies, user_agent):

    headers = {
        'Host': 'myriaverse-api.myria.com',
        'User-Agent': user_agent,
        'Accept': 'application/json',
        'Accept-Language': 'en-US,en;q=0.5',
        # 'Accept-Encoding': 'gzip, deflate',
        'Referer': 'https://myriaverse-api.myria.com/',
        'Origin': 'https://myria.com',
        'Dnt': '1',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Gpc': '1',
        # Requests doesn't support trailers
        # 'Te': 'trailers',
    }

    response = requests.get(
        'https://myriaverse-api.myria.com/v1/time',
        headers=headers, proxies=proxies, verify=False
    )

    if response.status_code != 200:
        logger.error(f'code: tXdG66MU; {response.status_code} {response.text}')
        return {'status': 'error'}
    if not response.text or not response.json():
        logger.error(f'code: eyrErC4m; {response.text}')
        return {'status': 'error'}

    if response.json()['status'] != 'success':
        logger.error(f'code: 5CB6nm78;{response.text}')
        return {'status': 'error'}
    if not response.json()['data']:
        logger.error(f'code: 9TEttF6r;{response.text}')
        return {'status': 'error'}

    return {
        'status': 'success',
        'data': {
            'time': response.json()['data']['time']
        }
    }

def connect_wallet(wallet_address, signed_message, message, proxies, user_agent):

    headers = {
        'Host': 'myriaverse-api.myria.com',
        'User-Agent': user_agent,
        'Accept': 'application/json',
        'Accept-Language': 'en-US,en;q=0.5',
        # 'Accept-Encoding': 'gzip, deflate',
        'Referer': 'https://myriaverse-api.myria.com/',
        # Already added when you pass json=
        # 'Content-Type': 'application/json',
        # 'Content-Length': '263',
        'Origin': 'https://myria.com',
        'Dnt': '1',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Gpc': '1',
        # Requests doesn't support trailers
        # 'Te': 'trailers',
    }

    json_data = {
        'wallet_id': wallet_address,
        'signature': signed_message,
        'message': message,
    }

    response = requests.post(
        'https://myriaverse-api.myria.com/v1/accounts/login/wallet',
        headers=headers, json=json_data, proxies=proxies, verify=False
    )

    if response.status_code != 200:
        logger.error(f'code: Rw5dH6WF; {response.status_code} {response.text}')
        return {'status': 'error'}
    if not response.text or not response.json():
        logger.error(f'code: Ecedn2Up; {response.text}')
        return {'status': 'error'}

    if response.json()['status'] != 'success':
        logger.error(f'code: X89HrtH8;{response.text}')
        return {'status': 'error'}
    if not response.json()['data']:
        logger.error(f'code: Wyd3zYfV;{response.text}')
        return {'status': 'error'}

    return {
        'status': 'success',
        'data': {
            'cookies': {
                'session': response.cookies['session'],
                'access_token': response.cookies['access_token'],
                'refresh_token': response.cookies['refresh_token']
            },
            'account': {
                'user_id': response.json()['data']['user_id'],
                'updated_on': response.json()['data']['updated_on'],
                'wallet_id': response.json()['data']['wallet_id'],
                'user_roles': response.json()['data']['user_roles'],
                'last_activity': response.json()['data']['last_activity'],
                'created_on': response.json()['data']['created_on']
            }
        }
    }

def choice_alliance(alliance_id, cookies, proxies, user_agent):

    cookies = {
        'session': cookies['session'],
        'access_token': cookies['access_token'],
        'refresh_token': cookies['refresh_token'],
    }

    headers = {
        'Host': 'myriaverse-api.myria.com',
        'User-Agent': user_agent,
        'Accept': 'application/json',
        'Accept-Language': 'en-US,en;q=0.5',
        # 'Accept-Encoding': 'gzip, deflate',
        'Referer': 'https://myriaverse-api.myria.com/',
        # Already added when you pass json=
        # 'Content-Type': 'application/json',
        # 'Content-Length': '30',
        'Origin': 'https://myria.com',
        'Dnt': '1',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Gpc': '1',
        # Requests doesn't support trailers
        # 'Te': 'trailers',
        # Requests sorts cookies= alphabetically
        # 'Cookie': f'session={session}; access_token={access_token}; refresh_token={refresh_token}',
    }

    json_data = {
        'alliance_id': alliance_id,
    }

    response = requests.post(
        'https://myriaverse-api.myria.com/v1/sigil/users/alliance',
        cookies=cookies, headers=headers, json=json_data, proxies=proxies, verify=False
    )

    if response.status_code != 200:
        logger.error(f'code: 6R8mJJmP; {response.status_code} {response.text}')
        return {'status': 'error'}
    if not response.text or not response.json():
        logger.error(f'code: 3dC5YSXE; {response.text}')
        return {'status': 'error'}

    if response.json()['status'] != 'success':
        logger.error(f'code: j5pyAKk3;{response.text}')
        return {'status': 'error'}

    return {
        'status': 'success',
        'data': {}
    }

def create_account_mission(first_name, last_name, username, password, email, referral_code, cookies, proxies, user_agent):

    cookies = {
        'session': cookies['session'],
        'access_token': cookies['access_token'],
        'refresh_token': cookies['refresh_token'],
    }

    headers = {
        'Host': 'myriaverse-api.myria.com',
        'User-Agent': user_agent,
        'Accept': 'application/json',
        'Accept-Language': 'en-US,en;q=0.5',
        # 'Accept-Encoding': 'gzip, deflate',
        'Referer': 'https://myriaverse-api.myria.com/',
        # Already added when you pass json=
        # 'Content-Type': 'application/json',
        # 'Content-Length': '145',
        'Origin': 'https://myria.com',
        'Dnt': '1',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Gpc': '1',
        # Requests doesn't support trailers
        # 'Te': 'trailers',
        # Requests sorts cookies= alphabetically
        # 'Cookie': f'session={session}; access_token=access_token; refresh_token={refresh_token}',
    }

    json_data = {
        'first_name': first_name,
        'last_name': last_name,
        'username': username,
        'password': password,
        'email': email,
        'redirect': 0,
    }
    if referral_code: json_data['referral_code'] = referral_code

    response = requests.post(
        'https://myriaverse-api.myria.com/v1/accounts/link',
        cookies=cookies, headers=headers, json=json_data, verify=False
    )

    # print(cookies, headers, json_data)

    if response.status_code != 200:
        logger.error(f'code: tLV5YRmc; {response.status_code} {response.text}')
        return {'status': 'error'}
    if not response.text or not response.json():
        logger.error(f'code: DVz2M5UC; {response.text}')
        return {'status': 'error'}

    if response.json()['status'] != 'success':
        logger.error(f'code: 9mtBJSdU;{response.text}')
        return {'status': 'error'}
    if not response.json()['data']:
        logger.error(f'code: GGeaTG53;{response.text}')
        return {'status': 'error'}

    return {
        'status': 'success',
        'data': response.json()['data']
    }

def get_email_verification_url(email, _from, subject, proxies, without_mail_id=None):

    parse_1secmail_mail_result = parse_1secmail_mail(email, _from, subject, proxies)
    if parse_1secmail_mail_result['status'] != 'success':
        logger.error('code: uNFr5wAn')
        return {'status': 'error'}

    mail_text_body = parse_1secmail_mail_result['data']['json']['textBody']
    url = mail_text_body[60:] # replace 'Please click the below url to verify your registration:\n    '

    return {
        'status': 'success',
        'data': {
            'url': url
        }
    }

def verify_email_with_requests(url, proxies, user_agent):

    headers = {
        'Host': 'myriaverse-api.myria.com',
        'User-Agent': user_agent,
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.5',
        # 'Accept-Encoding': 'gzip, deflate',
        'Dnt': '1',
        'Upgrade-Insecure-Requests': '1',
        'Sec-Fetch-Dest': 'document',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'none',
        'Sec-Fetch-User': '?1',
        'Sec-Gpc': '1',
        # Requests doesn't support trailers
        # 'Te': 'trailers',
    }

    response = requests.get(url, headers=headers, proxies=proxies, verify=False)

    print(f'\n\n{response.status_code} {response.text}\n\n')

    # if response.status_code != 200:
    #     logger.error(f'code: TvF5R7Tx; {response.status_code} {response.text}')
    #     return {'status': 'error'}
    # if not response.text:
    #     logger.error(f'code: XWtz7R72; {response.text}')
    #     return {'status': 'error'}

    # data = '<p>Found. Redirecting to <a href="https://myria.com/sigil">https://myria.com/sigil</a></p>'
    # if not data in response.text:
    #     logger.error(f'code: EWd6bW9h; {response.text}')
    #     return {'status': 'error'}

    return {'status': 'success'}

def verify_email(url, proxies, user_agent):
    
    session = HTMLSession()
    response = session.get(url, proxies=proxies, timeout=(27,27), verify=False)
    # response.html.render(timeout=27)

    if response.status_code != 200:
        logger.error(f'code: ed4qK5X6; {response.status_code} {response.text}')
        return {'status': 'error'}
    if not response.text:
        logger.error(f'code: fUq7r9JW; {response.text}')
        return {'status': 'error'}

    # data = '<p>Found. Redirecting to <a href="https://myria.com/sigil">https://myria.com/sigil</a></p>'
    # if not data in response.text:
    #     logger.error(f'code: M4e4LvED; {response.text}')
    #     return {'status': 'error'}

    data = 'Myria is a blockchain gaming ecosystem powered by'
    if not data in response.text:
        logger.error(f'code: M4e4LvED; {response.text}')
        return {'status': 'error'}

    return {'status': 'success'}
